//
//  MiddleManMyVC.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/15.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//
#define scrollViewHeight (UIScreenHeight + 5)

#import "MiddleManMyVC.h"
#import "PhootSelecteView.h"
#import "Tools.h"
#import "DealerDataManage.h"
#import "TxtReadVc.h"
#import "VPImageCropperViewController.h"
#import "SettingsViewController.h"

#import "MyOrderViewPageVc.h"
#import "LineBelowOrderViewController.h"
#import "MyCutomerVc.h"
#import "LineBelowOrderVc.h"
#import "MoneyManageVc.h"

#import "BrokerDataMange.h"
#import "UserModal.h"
#import "BrokerInfoModel.h"
#import "UIButton+WebCache.h"
#import "StringTool.h"
#import "MiddleManInfoEditVc.h"
#import "CalculatorViewController.h"
#import "FinshOrderVC.h"
#import "MessageVC.h"
#import "MessBtn.h"
#import "MessageDM.h"



@interface MiddleManMyVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *mainView;

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UILabel *perInfoLab;


@property (weak, nonatomic) IBOutlet UILabel *orderNumLab;
@property (weak, nonatomic) IBOutlet UILabel *customerNumLab;


@property (weak, nonatomic) IBOutlet UIButton *dealBtn;
@property (weak, nonatomic) IBOutlet UIButton *customerBtn;
@property (weak, nonatomic) IBOutlet UIButton *applyBtn;
@property (weak, nonatomic) IBOutlet UIButton *settingBtn;
@property (weak, nonatomic) IBOutlet UIButton *aboutUsBtn;
@property (weak, nonatomic) IBOutlet UIView *labView;

@property (weak, nonatomic) IBOutlet UIButton *headBtn;

@property (strong, nonatomic) BrokerDataMange *dataManage;
@property (strong, nonatomic) BrokerInfoModel *model;
@property(nonatomic,assign) Boolean needRefresh;

@property (weak, nonatomic) IBOutlet UILabel *finshOrderLab;

@property (nonatomic,strong)PhootSelecteView *menuView;
@property DealerDataManage *dm;
@property (nonatomic,strong)MessBtn *messBtn;


- (IBAction)clickBtn:(UIButton *)sender;


@end

@implementation MiddleManMyVC
@synthesize menuView,dm,needRefresh;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    
    needRefresh = true;
}



-(void)refreshMsgNotReadCount{

     self.messBtn.badge = [NSString stringWithFormat:@"%ld",(long)[MessageDM getMessageNotReadCount]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (needRefresh) {
        [self refreshData];
    }
    needRefresh = false;
    
    self.messBtn.badge = [NSString stringWithFormat:@"%ld",(long)[MessageDM getMessageNotReadCount]];
    
}

-(BrokerDataMange *)dataManage
{
    if (!_dataManage)
    {
        _dataManage = [[BrokerDataMange alloc]init];
    }
    return _dataManage;
}


-(void)initView
{
    [self.titleView setMianTitle:@"我的"];
    
    self.mainView.showsVerticalScrollIndicator = NO;
    self.titleView.doneBtn.hidden = YES;
    [self.labView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.33]];
    [self.titleView.doneBtn removeFromSuperview];
    
    self.messBtn = [MessBtn buttonWithType:UIButtonTypeCustom];
    self.titleView.doneBtn.hidden = YES;
    [self.messBtn setFrame:CGRectMake(PMW-60,0,60, 44)];
    [self.messBtn setShowsTouchWhenHighlighted:YES];
    [self.messBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [self.messBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [self.messBtn setImage:[UIImage imageNamed:@"messbtn"] forState:UIControlStateNormal];
    
    [self.messBtn addTarget:self action:@selector(messBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview:self.messBtn];

    
    self.titleView.backBtn.hidden = YES;
    self.titleView.backBtn.enabled = NO;
    self.mainView.frame = CGRectMake(0, 0, UIScreenWidth, scrollViewHeight);
    
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headViewHandleSingleTap:)];
    [self.headerView addGestureRecognizer:singleTap];
    
     dm = [[DealerDataManage alloc]init];
    
    
}

-(void)messBtnOnClick{
    
    MessageVC *vc = [MessageVC new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)refreshData{
    [super refreshData];

    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSInteger customerId = [UserModal shareUserModel].userId;
       ResulteMod *mod =  [bself.dataManage refeshDataBrokerInfoWithCustomerId:customerId];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            
            if (mod.resltState == ResultFail)
            {
                [MBProgressHUD showError:mod.resultTip];
            }else if(mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络出错"];
            }
            else
            {
                bself.model = [BrokerInfoModel brokerWithDic:mod.dataMod];
                [bself upDataUI];
                
            }
        });
    });
}

-(void)upDataUI
{
    [self.headBtn setBackgroundColor:NoImgColor];
    
    [self.headBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.avatar] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headtop_pic"]];
  
    
    self.orderNumLab.text = [NSString stringWithFormat:@"%zd",self.model.orders];
    self.finshOrderLab.text = [NSString stringWithFormat:@"%zd",self.model.orders];
    self.customerNumLab.text = [NSString stringWithFormat:@"%zd",self.model.consumers];
    
   if (![StringTool isBlankString:self.model.nickname])
    {
        self.perInfoLab.text = [NSString stringWithFormat:@"%@",self.model.nickname];
        if (![StringTool isBlankString:self.model.company])
        {
            self.perInfoLab.attributedText = [self dealStr:[NSString stringWithFormat:@"%@(%@)",self.model.nickname,self.model.company]];

        }
    }
    
}


-(NSMutableAttributedString *)dealStr:(NSString *)str
{
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:str];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:16.0]
     
                          range:NSMakeRange(0, self.model.nickname.length)];
    
    return AttributedStr;
    
}
#pragma mark 跳转到我的资料那一页
-(void)headViewHandleSingleTap:(UITapGestureRecognizer*)sender{
   
    needRefresh = true;
    MiddleManInfoEditVc *vc1 = [[MiddleManInfoEditVc alloc]initWithNibName:@"MiddleManInfoEditVc" bundle:nil];
    vc1.model = self.model;
    vc1.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc1 animated:YES];
    
    
}

#pragma mark 点击“交易管理，客户管理，线下下单申请，系统设置，关于我们
- (IBAction)clickBtn:(UIButton *)sender {
    NSInteger tag = sender.tag;
    switch (tag) {
        case 0: //交易管理
            
        {
            MyOrderViewPageVc *vc = [[MyOrderViewPageVc alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }

            
            break;
        case  1://客户管理
            
        {
            needRefresh = true;
            MyCutomerVc *vc = [[MyCutomerVc alloc]init];
            vc.isHidden = NO;
            vc.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case  2://线下下单申请
            
        {
            LineBelowOrderVc *vc = [[LineBelowOrderVc alloc]initWithNibName:@"LineBelowOrderVc" bundle:nil];
            vc.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:vc animated:YES];
        }

            break;
        case  3://系统设置
        {
            SettingsViewController *vc = [[SettingsViewController alloc]initWithNibName:@"SettingsViewController" bundle:nil];
            vc.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case  4://房贷计算器
              {
                  CalculatorViewController *vc = [CalculatorViewController new];
                  vc.hidesBottomBarWhenPushed = YES;

                  [self.navigationController pushViewController:[CalculatorViewController new] animated:YES];
                  
              }
            break;
        case  5://已完成订单
        {
            FinshOrderVC *vc = [FinshOrderVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            
//            if (self.menuView==nil) {
//                menuView = [PhootSelecteView creadInstance];
//                [menuView.tackPicBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
//                [menuView.selectePicBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
//            }
//            [menuView showInView:self.view];
            break;
        default:
            break;
    }
}


- (IBAction)headBtnOnClick:(id)sender {
    
    if (self.menuView==nil) {
        menuView = [PhootSelecteView creadInstance];
        [menuView.tackPicBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
        [menuView.selectePicBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    [menuView showInView:self.view];

}


-(void)btnOnclick:(id)sender{
    
    if (sender==menuView.tackPicBtn) {
        
        // 跳转到相机
        NSUInteger sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
    }else if(sender==menuView.selectePicBtn){
        
        // 跳转到相册
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}



#pragma mark 上传头像
-(void)upImg:(UIImage*)img{
    
    [menuView hide];
    
    [dm upHeadImg:img View:self.headBtn];
}




#pragma mark  UiPickView delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    image = [Tools fixOrientation:image];
    
    int h = [Tools getHightDifPMsW:100/2 sh:100/2 nw:PMW];
    CGRect buf = CGRectMake(0, PMH/2-h/2,PMW, h);
    
    // 裁剪
    VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:image cropFrame:buf limitScaleRatio:6];
    imgEditorVC.delegate = self;
    [self presentViewController:imgEditorVC animated:YES completion:^{}];
    
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}





#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)image {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
    
    image = [Tools imageWithImageSimple:image scaledToSize:CGSizeMake(100, 100)];
    
    [self upImg:image];
}



- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
}
- (IBAction)clickCostomerNumBtn:(id)sender {
    
    MyCutomerVc *vc = [[MyCutomerVc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
